package com.pay.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.pay.omni.OmniConfig;
import com.pay.omni.OmniCoreUtils;
import com.pay.omni.reponse.OmniTokenBalWithAddressRes;
import com.pay.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.functors.ConstantFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.common.base.BaseService;
import com.pay.common.support.Convert;
import com.pay.mapper.auto.OmniAddressMapper;
import com.pay.model.auto.OmniAddress;
import com.pay.model.auto.OmniAddressExample;
import com.pay.model.custom.Tablepar;
import com.pay.util.SnowflakeIdWorker;

/**
 * Service
 * @Title: OmniAddressService.java 
 * @Package com.pay.service 
 * @author fuce
 * @email 87766867@qq.com
 * @date 2019-08-07 13:05:23  
 */
@Slf4j
@Service
public class OmniAddressService implements BaseService<OmniAddress, OmniAddressExample> {
    @Autowired
    private OmniAddressMapper omniAddressMapper;
    @Autowired
    private OmniCoreUtils omniCoreUtils;
    @Autowired
    private OmniConfig omniConfig;

    public Object listenWallet() throws Exception {
        log.info("-------开始归集-------");
        // 钱包记录
        List<OmniTokenBalWithAddressRes> allBalancesWithAddress = omniCoreUtils.getAllBalancesWithAddress();
        // 遍历
        allBalancesWithAddress.stream().forEach(addr ->{
            try {
                // 平台地址除外
                if(addr.getAddress().equals(omniConfig.getPlatformAddress())){
                    return;
                }
                List<OmniTokenBalWithAddressRes.BalancesBean> balances = addr.getBalances();
                log.info("地址{}獲得的錢包集合：{}", addr.getAddress(), JSON.toJSONString(balances));
                for(OmniTokenBalWithAddressRes.BalancesBean balancesBean: balances){
                    // 不是usdt时
                    if(omniConfig.getPropertyId().longValue() != balancesBean.getPropertyid()){
                        log.info("地址{}的錢包{}的令牌id不是{}", addr.getAddress(), JSON.toJSONString(balancesBean), omniConfig.getPropertyId());
                        continue;
                    }
                    // 钱少于sendMin时
                    BigDecimal value = balancesBean.getBalance();
                    BigDecimal minCollectionAmount = BigDecimal.valueOf(Double.valueOf(100));
                    if(value.compareTo(minCollectionAmount) < 0){
                        log.info("地址{}的手續費不夠：{}", addr.getAddress(), JSON.toJSONString(balancesBean));
                        continue;
                    }
                    // 转账
                    String referenceaddress = getReferenceaddress();
                    log.info("地址{}轉賬到{}地址,利息地址{},,犀利-開始", addr.getAddress(), referenceaddress, omniConfig.getPlatformAddress());
                    String txid = omniCoreUtils.sendOmniToken(addr.getAddress(), referenceaddress, omniConfig.getPropertyId(), value, omniConfig.getPlatformAddress());
                    log.info("地址{}轉賬到{}地址中-結束,txid={}", addr.getAddress(), referenceaddress, txid);
                }
            } catch (Exception e){
                log.info("归集错误---------" + e.getMessage());
                e.printStackTrace();
            }
        });
        return allBalancesWithAddress;
    }

    /**
     * 轮训获取集合地址
     * @return
     */
    public String getReferenceaddress(){
        Calendar rightNow = Calendar.getInstance();
        int day = rightNow.get(Calendar.DAY_OF_MONTH);
        List<String> referenceAddress = omniConfig.getReferenceaddress();

        return referenceAddress.get(day%referenceAddress.size());
    }

    public void insertOrUpdateAddressWallet() throws Exception {
        log.info("-----------更新地址信息开始----------------");
        List<OmniTokenBalWithAddressRes> allBalancesWithAddress = omniCoreUtils.getAllBalancesWithAddress();
        Map<String, OmniTokenBalWithAddressRes> allBalanceMap = CommonUtils.listToMap(allBalancesWithAddress, "address");
        List<String> allBalanceList = Lists.newArrayList(allBalanceMap.keySet());
        // db系统数据
        List<OmniAddress> omniBalances = omniAddressMapper.select(OmniAddress.builder().addressList(allBalanceList).build());
        Map<String, List<OmniAddress>> addressListMap = CommonUtils.listToMapList(omniBalances, "address");
        List<String> addressList = Lists.newArrayList(addressListMap.keySet());
        // 修改成0
        omniAddressMapper.updateValueToZero(OmniAddress.builder().addressList(addressList).build());
        // 合并金额
        OmniTokenBalWithAddressRes res;
        Integer id;
        List<OmniTokenBalWithAddressRes.BalancesBean> balances;
        // 修改部分
        OmniAddress omniBalance;
        List<OmniAddress> omniBalanceList;
        Map<String, OmniAddress> balanceMap;
        for(String address: allBalanceList){
            res = allBalanceMap.get(address);
            balances = res.getBalances();
            // db
            omniBalanceList = addressListMap.get(address);
            balanceMap = CommonUtils.listToMap(omniBalanceList, "id");
            // 合并
            for(OmniTokenBalWithAddressRes.BalancesBean bean: balances){
                id = Integer.valueOf(String.valueOf(bean.getPropertyid()));
                omniBalance = balanceMap.get(String.valueOf(id));
                if(null == omniBalance){
                    omniAddressMapper.insert(OmniAddress.builder()
                            .propertyid(Long.valueOf(id))
                            .address(address)
                            .name(bean.getName())
                            .balance(bean.getBalance())
                            .frozen(bean.getFrozen())
                            .reserved(bean.getReserved())
                            .build());
                    log.info("地址({})初始化金额，value=({}),frozen=({})", address, bean.getBalance(), bean.getFrozen());
                } else if(omniBalance.getBalance().compareTo(bean.getBalance()) != 0
                        || omniBalance.getFrozen().compareTo(bean.getFrozen()) != 0) {
                    omniAddressMapper.updateByPrimaryKeySelective(OmniAddress.builder().address(address)
                            .propertyid(Long.valueOf(id)).balance(bean.getBalance()).build());
                    log.info("地址({})的金额发送变动，value=({}),frozen=({})", address, bean.getBalance(), bean.getFrozen());
                }
            }
        }
    }

    /**
     * 分页查询
     * @param tablepar
     * @param name
     * @return
     */
    public PageInfo<OmniAddress> list(Tablepar tablepar, String name) {
            OmniAddressExample testExample = new OmniAddressExample();
        testExample.setOrderByClause("balance desc");
        if (name != null && !"".equals(name)) {
            testExample.createCriteria().andNameLike("%" + name + "%");
        }

        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
        List<OmniAddress> list = omniAddressMapper.selectByExample(testExample);
        PageInfo<OmniAddress> pageInfo = new PageInfo<OmniAddress>(list);
        return pageInfo;
    }

            @Override
        public int deleteByPrimaryKey(String ids) {
            return 0;
        }


        @Override
        public OmniAddress selectByPrimaryKey(String id) {

            return omniAddressMapper.selectByPrimaryKey(id);
        }


        @Override
        public int updateByPrimaryKeySelective(OmniAddress record) {
            return omniAddressMapper.updateByPrimaryKeySelective(record);
        }

    /**
     * 添加
     */
    @Override
    public int insertSelective(OmniAddress record) {
        return 0;
    }


    @Override
    public int updateByExampleSelective(OmniAddress record, OmniAddressExample example) {

        return omniAddressMapper.updateByExampleSelective(record, example);
    }


    @Override
    public int updateByExample(OmniAddress record, OmniAddressExample example) {

        return omniAddressMapper.updateByExample(record, example);
    }

    @Override
    public List<OmniAddress> selectByExample(OmniAddressExample example) {

        return omniAddressMapper.selectByExample(example);
    }


    @Override
    public long countByExample(OmniAddressExample example) {

        return omniAddressMapper.countByExample(example);
    }


    @Override
    public int deleteByExample(OmniAddressExample example) {

        return omniAddressMapper.deleteByExample(example);
    }

    /**
     * 检查name
     * @param omniAddress
     * @return
     */
    public int checkNameUnique(OmniAddress omniAddress) {
            OmniAddressExample example = new OmniAddressExample();
        example.createCriteria().andNameEqualTo(omniAddress.getName());
        List<OmniAddress> list = omniAddressMapper.selectByExample(example);
        return list.size();
    }


}
